<script setup lang="ts">
import {
  NButton,
  NDataTable,
  useMessage,
  NForm,
  NPagination,
  NFormItem,
  NInput,
  NSelect,
  NDatePicker,
  NInputNumber,
  NTreeSelect,
  NImage,
  type UploadFileInfo,
  type SelectOption,
  type DataTableColumns,
  type FormInst,
  NFlex,
  NTooltip
} from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { ref, h, reactive, onMounted, computed } from 'vue'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import type { BatchItemModel, BatchDetailModel } from '@/api/batchV2'
import useRouteReplace from '@/hooks/useRouteReplace'
import useFlush from '@/hooks/useFlush'
import type { DicTreeModel } from '@/api/dic'
import VBackImg from '@/assets/images/back.png'
import VAttachments from '@/views/OA/Common/Attachments.vue'
import BatchCres from './components/BatchCres.vue'

const message = useMessage()
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
useFlush('flushEditBatchTable', () => queryTableData(true))

const clueSelectOptions = ref<SelectOption[]>([])
const clueSelectLoading = ref(false)
const queryClueSelectOptions = async () => {
  clueSelectLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'batchV2',
      api: 'clueList'
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    clueSelectLoading.value = false
  }
}

const clueMethodOptions = reactive<DicTreeModel[]>([])
const clueMethodLoading = ref(false)
const queryClueMethodOptions = async () => {
  clueMethodLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'dic',
      api: 'getTree',
      override: {
        params: {
          dicCode: 'A30'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueMethodOptions.length = 0
    clueMethodOptions.push(...(res.data[0] ? res.data[0].children || [] : []))
  } catch (error) {
    console.error(error)
  } finally {
    clueMethodLoading.value = false
  }
}

const formInst = ref<FormInst | null>(null)
const batchInfo = ref({} as BatchDetailModel)
const isJCDG = computed(() => batchInfo.value.solicitMethodCode === 'A3007')
const queryBatchInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<BatchDetailModel>>({
    module: 'batchV2',
    api: 'detail',
    override: {
      params: {
        id: route.params.id
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.data.endTime) {
    res.data.endTime = res.data.endTime.slice(0, 10)
  }
  if (res.data.startTime) {
    res.data.startTime = res.data.startTime.slice(0, 10)
  }
  if (res.data.solicitNum) {
    res.data.solicitNum = Number(res.data.solicitNum)
  }
  batchInfo.value = res.data
  if (res.data.fileIds) queryFileList(res.data.fileIds)
}

const fileList = ref<UploadFileInfo[]>([])
const queryFileList = async (filesIds: string) => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: filesIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    fileList.value = res.data.map((e) => ({
      id: e.id,
      path: e.path,
      name: e.name,
      url: e.path,
      status: 'success'
    })) as unknown as UploadFileInfo[]
  } catch (error) {
    console.error(error)
  }
}

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const columns: DataTableColumns<BatchItemModel> = [
  {
    key: 'index',
    title: '序号',
    width: 80,
    align: 'center',
    render: (_, i) => i + 1
  },
  {
    title: '类型',
    key: 'itemTypeName'
  },
  {
    title: '名称',
    key: 'itemName'
  },
  {
    title: '数量',
    key: 'itemNum'
  },
  {
    title: '年代',
    key: 'years'
  },
  {
    title: '备注',
    key: 'remark'
  },
  {
    title: '图片',
    key: 'imageIds',
    render({ _imageFiles }) {
      if (!_imageFiles) return
      return h(
        NFlex,
        {},
        {
          default: () =>
            _imageFiles.map((e) =>
              h(NImage, {
                src: e.path,
                width: 50
              })
            )
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    render: (e) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: {
            display: e.detail ? 'inline-flex' : 'none'
          },
          onClick: () => {
            router.push({
              name: 'detailBatchItem',
              params: {
                id: route.params.id,
                clueId: batchInfo.value.clueId,
                itemId: e.id
              },
              query: {
                type: 'r',
                redirect: route.fullPath
              }
            })
          }
        },
        {
          default: () => '详情'
        }
      )
    ]
  }
]

const tableLoading = ref(false)
const tableData = ref<BatchItemModel[]>([])
const queryTableData = async (flush = false) => {
  tableLoading.value = true
  if (flush) paginationReactive.page = 1
  const [error, res] = await sendRequest<HttpResponsePagination<BatchItemModel>>({
    module: 'batchV2',
    api: 'batchItems',
    override: {
      params: {
        batchId: route.params.id,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list

  tableData.value.forEach((item) => {
    if (!item.imageIds) return
    sendRequest({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: item.imageIds
        }
      }
    }).then(([error, res]) => {
      if (error || res.code !== 0) return
      item._imageFiles = res.data
    })
  })
}

onMounted(() => {
  queryClueSelectOptions()
  queryClueMethodOptions()
  queryBatchInfo()
  queryTableData()
})
</script>

<template>
  <div class="batch-noIdentify-detail">
    <div class="ac-title">鉴定流程</div>
    <div class="ac-flow ac-card">
      <div class="step finished">无需鉴定</div>
    </div>
    <div class="br"></div>

    <div class="ac-title">批次信息</div>
    <NForm
      ref="formInst"
      :model="batchInfo"
      disabled
      label-placement="left"
      label-width="100rem"
      :show-feedback="false"
      :show-require-mark="false"
      class="ac-card form"
    >
      <NFormItem label="关联线索：">
        <NSelect
          :value="batchInfo.clueId"
          :options="clueSelectOptions"
          :loading="clueSelectLoading"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="批次名称：">
        <NTooltip :max-width="350">
          <template #trigger>
            <NInput
              :value="batchInfo.name"
              placeholder="/"
            />
          </template>
          {{ batchInfo.name }}
        </NTooltip>
      </NFormItem>
      <NFormItem label="征集方式：">
        <NTreeSelect
          :value="batchInfo.solicitMethodCode"
          :options="clueMethodOptions"
          :loading="clueMethodLoading"
          placeholder="/"
          key-field="code"
          label-field="name"
        />
      </NFormItem>
      <NFormItem label="接收时间：">
        <NDatePicker
          :formatted-value="batchInfo.receiveTime"
          type="datetime"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="移交人：">
        <NInput
          :value="batchInfo.transferor"
          placeholder="/"
        />
      </NFormItem>

      <NFormItem label="移交人电话：">
        <NInput
          :value="batchInfo.transferorPhone"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="接收人：">
        <NInput
          :value="batchInfo.receiver"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="征集数量：">
        <NInputNumber
          :value="batchInfo.solicitNum"
          placeholder="/"
          :show-button="false"
          :min="0"
          :max="Number.MAX_SAFE_INTEGER"
        />
      </NFormItem>
      <NFormItem label="证书发放：">
        <BatchCres :batch-id="batchInfo.id" />
      </NFormItem>
      <template v-if="isJCDG">
        <NFormItem label="开始时间：">
          <NDatePicker
            :formatted-value="batchInfo.startTime"
            type="date"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="结束时间：">
          <NDatePicker
            :formatted-value="batchInfo.endTime"
            type="date"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="代存期限：">
          <NInput
            :value="batchInfo.depositPeriod"
            placeholder="/"
          />
        </NFormItem>
      </template>

      <NFormItem
        label="备注："
        class="n-form-item--textarea"
      >
        <NInput
          :value="batchInfo.remark"
          type="textarea"
          placeholder="/"
          rows="5"
        />
      </NFormItem>

      <NFormItem label="附件：">
        <VAttachments
          v-if="batchInfo.fileIds"
          :attach-list="fileList"
        />
      </NFormItem>
    </NForm>

    <div class="br"></div>

    <div class="ac-title">物品信息</div>
    <div class="ac-card dc">
      <NDataTable
        :columns="columns"
        :data="tableData"
        :loading="tableLoading"
      />
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </div>
  </div>

  <FixedAction>
    <div class="batch-noIdentify-detail-buttons">
      <NButton
        ghost
        @click="routeReplace"
        :style="`width: 78px; color: #5fb17f`"
      >
        <template #icon>
          <NImage
            :src="VBackImg"
            :style="`width: 50rem; height: 50rem`"
            preview-disabled
          ></NImage>
        </template>
        返回
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.ac-flow {
  display: flex;
  align-items: center;
  padding: 20rem 20rem 30rem;
  gap: 0 1.5em;

  .step {
    padding: 10rem 15rem;
    background-color: #e1e1e1;

    &.finished {
      color: #fff;
      background-color: #6cb187;
    }
  }
}

.batch-noIdentify-detail {
  min-height: 100%;
  padding: 15rem 0 130rem;
  background-color: #f0efee;

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .ac-card {
    padding: 20rem;
    background-color: #e1e1e1;

    &.dc {
      display: flex;
      flex-direction: column;
      gap: 16rem 0;
    }

    &.form {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 6rem 30rem;

      .n-form-item--textarea {
        grid-column: 1 / -1;
      }

      .n-date-picker,
      .n-input-number {
        flex: 1;
      }
    }
  }

  .ac-title {
    font-size: 26rem;
    margin-bottom: 30rem;
    color: #048c5e;
    line-height: 1;
  }
}

.batch-noIdentify-detail-ctl-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 0 16rem;
}

.batch-noIdentify-detail-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
</style>
